package com.mali.common.web.advice;

import com.mali.common.dto.Result;
import com.mali.common.exception.BizException;
import com.mali.common.exception.UnAuthException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import javax.validation.constraints.NotNull;

@Slf4j
@RestControllerAdvice
public class CommonAdviser {
    @ExceptionHandler(BizException.class)
    public Result<?> handleBizException(@NotNull BizException e) {
        return Result.fail(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(UnAuthException.class)
    public Result<?> handleUnAuthException(@NotNull UnAuthException e) {
        return Result.fail(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getFieldErrors().stream()
                .map(fieldError -> fieldError.getField() + ": " + fieldError.getDefaultMessage())
                .findFirst()
                .orElse(e.getMessage());
        log.warn("参数校验异常: {}", message);
        return Result.fail(400, "参数错误: " + message);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public Result<?> handleConstraintViolationException(ConstraintViolationException e) {
        String message = e.getConstraintViolations().stream()
                .map(cv -> cv.getPropertyPath() + ": " + cv.getMessage())
                .findFirst()
                .orElse(e.getMessage());
        log.warn("参数校验异常: {}", message);
        return Result.fail(400, "参数错误: " + message);
    }

    @ExceptionHandler(BindException.class)
    public Result<?> handleBindException(BindException e) {
        String message = e.getBindingResult().getFieldErrors().stream()
                .map(fieldError -> fieldError.getField() + ": " + fieldError.getDefaultMessage())
                .findFirst()
                .orElse(e.getMessage());
        log.warn("参数绑定异常: {}", message);
        return Result.fail(400, "参数错误: " + message);
    }

    @ExceptionHandler(Exception.class)
    public Result<?> handleException(@NotNull Exception e) {
        log.error("服务器异常", e);
        return Result.fail(500, "服务器异常：");
    }
}
